package com.szosen.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.measurement.MeasureECGActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/***
 * 这个使用第二个的方式打印心电波形，只和FileSaveUtil差不多。
 *
 */
public class FileSaveUtilecg2 {
    private static String sdState = Environment.getExternalStorageState();
    private static String path = Environment.getExternalStorageDirectory()
            .toString();
    private static String manbingPath = path;

    /***
     * 返回sd卡的路径位置
     *
     * @return
     */
    public static String getSDCardPath() {
        return path + "/" + MeasureECGActivity.FileName + "/";
    }

    /***
     *
     * @param pathName
     * @param fileName
     * @param fileContent
     */
    public static File saveTxtFile(String pathName, String fileName,
                                   String fileContent) {
        File file;
        File mainFile = null;
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            // 获得sd卡根目录
            file = new File(manbingPath, "/" + MeasureECGActivity.FileName
                    + "/" + pathName);
            if (!file.exists()) {
                file.mkdirs();
            }
            mainFile = new File(file, fileName + ".txt");
            try {
                if (!mainFile.exists()) {
                    mainFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(mainFile);
                // System.out.println("fileSaveUtil。savetxtfile内容"+fileContent);
                fos.write(fileContent.getBytes());
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mainFile;
    }

    public static void saveUserListTxtFile(String pathName, String fileName,
                                           String fileContent) {
        // File file;
        // File mainFile;
        // if (sdState.equals(Environment.MEDIA_MOUNTED)) {
        // // 获得sd卡根目录
        // file = new File(manbingPath, "/新达启帆/"+pathName);
        // if (!file.exists()) {
        // file.mkdirs();
        // }
        // mainFile = new File(file, fileName + ".txt");
        // try {
        // if (!mainFile.exists()) {
        // mainFile.createNewFile();
        // }
        // FileOutputStream fos = new FileOutputStream(mainFile);
        // System.out.println(fileContent);
        // fos.write(fileContent.getBytes());
        // fos.flush();
        // fos.close();
        // } catch (FileNotFoundException e) {
        // e.printStackTrace();
        // } catch (IOException e) {
        // e.printStackTrace();
        // }
        // }
    }

    // 将SD卡文件删除
    public static void deleteFile(File file) {
        if (sdState.equals(Environment.MEDIA_MOUNTED)) {
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                }
                // 如果它是一个目录
                else if (file.isDirectory()) {
                    // 声明目录下所有的文件 files[];
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                    }
                }
                file.delete();
            }
        }
    }

    /***
     * 保存pdf文件打印
     *
     * @param context
     * @param headContent
     *            头的内容
     * @param resultContent
     *            返回的心电诊断结论
     * @param pngPath
     *            图片缓存地址
     * @param filePath
     *            文件目录
     */
    public static void savePDFFile(final Context context,
                                   final String headContent, final String resultContent,
                                   final String pngPath, final String filePath, final String time) {
        new Thread() {
            public void run() {
                Document document = new Document(PageSize.A4.rotate(), 25, 20,
                        10, 10);
                try {
                    File pdfFile = new File(filePath);
                    FileOutputStream fos = new FileOutputStream(pdfFile);
                    PdfWriter.getInstance(document, fos);
                    // 打开document
                    document.open();
                    // 添加字体文件
                    BaseFont baseFontChinese = BaseFont.createFont(
                            "STSong-Light", "UniGB-UCS2-H",
                            BaseFont.NOT_EMBEDDED);
                    Font fontChinese = new Font(baseFontChinese, 14,
                            Font.NORMAL);
                    Chunk timeChunk = new Chunk(time, fontChinese);
                    // timeChunk.set
                    String birthday = BaseActivity.getHealthRecord()
                            .getBirthday();
                    int old = 0;
                    if (birthday.length() > 4) {
                        int now = Integer.valueOf(Tools.GetCurrentTime()
                                .substring(0, 4));
                        int bir = Integer.valueOf(birthday.substring(0, 4));
                        old = now - bir;
                    }
                    String sexCode = BaseActivity.getHealthRecord()
                            .getSexCode();
                    if ("1".equals(sexCode)) {
                        sexCode = "男";
                    } else if ("2".equals(sexCode)) {
                        sexCode = "女";
                    }
                    Paragraph head = new Paragraph(" 姓名： " + headContent
                            + "    性别：    " + sexCode + "    年龄：   "
                            + (old == 0 ? "" : "" + old).replace("+", "")
                            + "\n", fontChinese);
                    Paragraph result = new Paragraph(resultContent + "\n",
                            fontChinese);
                    Paragraph title = new Paragraph("心电诊断报告\n", new Font(
                            baseFontChinese, 16, Font.NORMAL));
                    Paragraph printTime = new Paragraph("打印时间："
                            + TimeHelper.getCurrentTime(), new Font(
                            baseFontChinese, 8, Font.NORMAL));
                    Paragraph doctor = new Paragraph(
                            "医生签名：                       ", new Font(
                            baseFontChinese, 16, Font.NORMAL));
                    printTime.setAlignment(Element.ALIGN_RIGHT);
                    doctor.setAlignment(Element.ALIGN_RIGHT);
                    title.setAlignment(Element.ALIGN_CENTER);// 居中显示
                    //
                    // 添加了图片
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    Bitmap bitmap = BitmapFactory
                            .decodeStream(new FileInputStream(new File(pngPath)));
                    Bitmap bitmap2 = small(bitmap);
                    document.setPageCount(1);
                    bitmap2.compress(Bitmap.CompressFormat.PNG /* FileType */,
                            100 /* Ratio */, stream);
                    Image jpg = Image.getInstance(stream.toByteArray());
                    //
                    //
                    AssetManager assetManager = context.getAssets();
                    InputStream is = assetManager.open("asign.png");
                    Bitmap asign = BitmapFactory.decodeStream(is);
                    Bitmap asign2 = small(asign, 0.15f, 0.15f);
                    ByteArrayOutputStream asignStream = new ByteArrayOutputStream();
                    asign2.compress(Bitmap.CompressFormat.PNG /* FileType */,
                            100 /* Ratio */, asignStream);
                    Image asignJpg = Image.getInstance(asignStream
                            .toByteArray());
                    // asign2.getWidth();
                    asignJpg.setAbsolutePosition(document.getPageSize()
                            .getWidth() - asign2.getWidth(), 0);
                    //
                    document.add(title);
                    document.add(head);
                    document.add(jpg);
                    document.add(printTime);
                    document.add(result);
                    document.add(asignJpg);
                    document.close();
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent();
                    // ComponentName comp = new ComponentName(
                    // "com.dynamixsoftware.printershare",
                    // "com.dynamixsoftware.printershare.ActivityPrintPDF");
                    // intent.setComponent(comp);
                    intent.setAction("android.intent.action.VIEW");
                    intent.setDataAndType(Uri.fromFile(pdfFile),
                            "application/msword");
                    context.startActivity(intent);
                } catch (Exception e) {
                    System.out.println("保存打印文件失败。。。");
                    e.printStackTrace();
                } finally {

                }
            }

            ;
        }.start();

    }

    /***
     * 保存一张尿液的pdf。写到文字中。
     */
    public static void saveNiaoyePdf(Context context, String pdfPath,
                                     String pdfName, String name, String sex, String yearsold,
                                     String checkTime, String glu, String leu, String bld, String ph,
                                     String pro, String ubg, String nit, String sg, String ket,
                                     String bil, String vc) {
        // 先打开document，然后获取文件流
        Document document = new Document(PageSize.A4);
        try {
            File pdfPathFile = new File(pdfPath);
            if (!pdfPathFile.exists()) {
                pdfPathFile.mkdirs();
            }
            File pdfFile = new File(pdfPathFile, pdfName);
            if (!pdfFile.exists()) {
                pdfFile.createNewFile();
            }
            PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            document.open();
            // 设置标题头
            Paragraph title = new Paragraph("尿液分析报告\n", getChineseFont(18));
            title.setAlignment(Element.ALIGN_CENTER);// 居中显示
            // 增加病人信息
            document.add(title);
            Paragraph userInfo = new Paragraph("  姓名： " + name + "  性别：    "
                    + sex + "  年龄：" + yearsold + "\n", getChineseFont(16));
            document.add(userInfo);
            document.add(new Paragraph("", getChineseFont(2)));
            // 增加尿液测量的项目参数、数据
            int cellCount = 6;
            PdfPTable table = getNiaoyetable(cellCount);
            Font font = getChineseFont(14);
            table.addCell(new Paragraph("序号", font));
            table.addCell(new Paragraph("英文代号", font));
            table.addCell(new Paragraph("项目", font));
            table.addCell(new Paragraph("结果", font));
            table.addCell(new Paragraph("单位", font));
            table.addCell(new Paragraph("参考值", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("1", font));
            table.addCell(new Paragraph("glu", font));
            table.addCell(new Paragraph("尿糖", font));
            table.addCell(new Paragraph(glu, font));
            table.addCell(new Paragraph("mmol/L", font));
            // 单位
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("2", font));
            table.addCell(new Paragraph("leu", font));
            table.addCell(new Paragraph("白细胞", font));
            table.addCell(new Paragraph(leu, font));
            table.addCell(new Paragraph("Cell/uL", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("3", font));
            table.addCell(new Paragraph("bld", font));
            table.addCell(new Paragraph("潜血", font));
            table.addCell(new Paragraph(bld, font));
            table.addCell(new Paragraph("", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("4", font));
            table.addCell(new Paragraph("ph", font));
            table.addCell(new Paragraph("酸碱度", font));
            table.addCell(new Paragraph(ph, font));
            table.addCell(new Paragraph("ph", font));
            table.addCell(new Paragraph("6.5-7.5", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("5", font));
            table.addCell(new Paragraph("pro", font));
            table.addCell(new Paragraph("蛋白质", font));
            table.addCell(new Paragraph(pro, font));
            table.addCell(new Paragraph("g/L", font));
            table.addCell(new Paragraph("6.5-7.5", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("6", font));
            table.addCell(new Paragraph("ubg", font));
            table.addCell(new Paragraph("尿胆原", font));
            table.addCell(new Paragraph(ubg, font));
            table.addCell(new Paragraph("umol/L", font));
            table.addCell(new Paragraph("3-16umol/L", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("7", font));
            table.addCell(new Paragraph("nit", font));
            table.addCell(new Paragraph("亚硝酸盐", font));
            table.addCell(new Paragraph(nit, font));
            table.addCell(new Paragraph("", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("8", font));
            table.addCell(new Paragraph("sg", font));
            table.addCell(new Paragraph("比重", font));
            table.addCell(new Paragraph(sg, font));
            table.addCell(new Paragraph("", font));
            table.addCell(new Paragraph("1.003-1.03", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("9", font));
            table.addCell(new Paragraph("ket", font));
            table.addCell(new Paragraph("尿酮体", font));
            table.addCell(new Paragraph(ket, font));
            table.addCell(new Paragraph("mmol/L", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("10", font));
            table.addCell(new Paragraph("bil", font));
            table.addCell(new Paragraph("胆红素", font));
            table.addCell(new Paragraph(bil, font));
            table.addCell(new Paragraph("umol/L", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);

            table = getNiaoyetable(cellCount);
            table.addCell(new Paragraph("11", font));
            table.addCell(new Paragraph("vc", font));
            table.addCell(new Paragraph("维生素C", font));
            table.addCell(new Paragraph(vc, font));
            table.addCell(new Paragraph("mmol/L", font));
            table.addCell(new Paragraph("-", font));
            document.add(table);
            Paragraph time = new Paragraph("测量时间：" + checkTime, font);
            time.setAlignment(Element.ALIGN_RIGHT);
            document.add(time);
            document.close();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent();
            // ComponentName comp = new ComponentName(
            // "com.dynamixsoftware.printershare",
            // "com.dynamixsoftware.printershare.ActivityPrintPDF");
            // intent.setComponent(comp);
            intent.setAction("android.intent.action.VIEW");
            intent.setDataAndType(Uri.fromFile(pdfFile), "application/msword");
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    private static PdfPTable getNiaoyetable(int cellCount) {
        PdfPTable table = new PdfPTable(cellCount);
        // table.setHorizontalAlignment(90);
        table.setWidthPercentage(100);
        return table;
    }

    /**
     * 保存一张心电的图片。
     */
    public static void saveEcgPNG(String pngPath, String pngName,
                                  int[] report1, String name, String sex, String idCard, String age,
                                  String checkTime, String result, String hospital,
                                  ArrayList<int[]> ecgDatas, boolean printResult) {
        Bitmap bitmap = Bitmap
                .createBitmap(2500, 1758, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        // 文字区域0-11 图片区域11-43;
        drawBackGround(canvas);
        if (checkTime.endsWith(".00")) {
            checkTime = checkTime.substring(0, checkTime.length() - 3);
        }
        checkTime = checkTime.replace("T", " ");
        drawECGResult(canvas, report1, name, sex, age, checkTime, idCard,
                result, hospital, printResult);
        drawECGValue(ecgDatas, canvas);
        saveBitmap(bitmap, pngPath, pngName);
    }

    /***
     * 保存一张带有结论的心电报告图片
     * @param basePicPath  不带结论的原图
     * @param result  结论
     */
    public static String saveECGResultPNG(String basePicPath, String result) {
        Bitmap bitmap = BitmapFactory.decodeFile(basePicPath).copy(Bitmap.Config.ARGB_8888, true);
        if (bitmap == null) {
            return "";
        }
        Canvas canvas = new Canvas(bitmap);
        int startX = canvas.getWidth() / 4 * 3 - 60;
        Paint textPaint = new Paint();
        int textSize = 42;
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextSize(textSize);
        textPaint.setColor(Color.BLACK);
        int maxLength = 15;
        if (result.length() > maxLength) {
            int length = result.length();
            int count = (length % maxLength == 0) ? length / maxLength : (length / maxLength + 1);
            for (int i = 0; i < count; i++) {
                int endIndex = (i + 1) * maxLength;
                if (endIndex > length) {
                    endIndex = length;
                }
                int startIndex = i * maxLength;
                String tempText = result.substring(startIndex, endIndex);
                canvas.drawText(tempText, startX, 702 + i * textSize, textPaint);
            }
        } else {
            canvas.drawText(result, startX, 702, textPaint);
        }
        String resultPicPath = basePicPath;
        if (resultPicPath.endsWith(".png")) {
            resultPicPath = resultPicPath.substring(0, resultPicPath.length() - 4) + "_结论.png";
        }
        saveBitmap(bitmap, resultPicPath);
        return resultPicPath;
    }


    /***
     *
     * @param bitmap
     *            bitmap
     * @param filePath
     *            文件保存的路径
     * @param fileName
     *            文件保存的名称 xxx.bmp xxx.png xxx.jpg
     */
    private static void saveBitmap(Bitmap bitmap, String filePath,
                                   String fileName) {
        FileOutputStream fos;

        try {
            File path = new File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(filePath, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            // FileSaveUtil.savePDFFile("姓名 \n", myScreenBitmap,
            // pdfFileName);
            // FileSaveUtil.savePDFFile("姓名是\n", file.getAbsolutePath(),
            // pdfFileName);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("Panel", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("Panel", "IOEception", e);
        }
    }

    /***
     *
     * @param bitmap
     *            bitmap
     * @param fileNamePath
     *            文件保存的路径
     */
    private static void saveBitmap(Bitmap bitmap, String fileNamePath) {
        FileOutputStream fos;

        try {
            File file = new File(fileNamePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            // FileSaveUtil.savePDFFile("姓名 \n", myScreenBitmap,
            // pdfFileName);
            // FileSaveUtil.savePDFFile("姓名是\n", file.getAbsolutePath(),
            // pdfFileName);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("Panel", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("Panel", "IOEception", e);
        }
    }

    /***
     * 网格的颜色。由于黄色的，用黑白打印不出来。
     */
    private static int color_wangge = Color.rgb(5, 5, 5);
    /***
     * 标题的颜色。原来是浅蓝色的，但是黑白打印不出来，所以改为黑色的。
     */
    private static int color_title = Color.BLACK;

    private static void drawBackGround(Canvas canvas) {
        int allWidth = canvas.getWidth(), allHeight = canvas.getHeight();

        /********** 画网格 **********/
        Paint mPaint = new Paint();
        mPaint.setColor(color_wangge);
        mPaint.setStrokeWidth(1.5f);
        canvas.drawColor(Color.WHITE);
        int height = canvas.getHeight();
        // 一共多少个大格子，就是多少厘米
        int geziCount = 27;
        // 1mm代表的宽度
        int mm1 = allWidth / (geziCount * 10);
        System.out.println("mm1的长度是：" + mm1);
        // 每隔5mm就画一线
        int mmH = mm1 * 5;
        // 取4分3的宽度
        int endX = canvas.getWidth() / 4 * 3 - 100;
        // y轴空白的高度，就是从上到下哪里开始画图。
        // 上下空白的距离。因为纸张在打印时上下会空一点白色的。
        int marginY = 10;
        // 图片的高度
        int picHeight = allHeight - marginY * 2;
        int startDrawY = allHeight - picHeight + marginY;
        for (int u = 0; u < endX; u += mm1) {
            if (u % mmH == 0) {
                canvas.drawLine(u, 0, u, height, mPaint); // 纵轴方向
            } else {
                // 纵轴方向每隔6px打点即1mm
                for (int i = 0; i < (height + mm1 - 1); i += mm1)
                    canvas.drawPoint(u, 0 + i, mPaint);
            }
        }
        // 一横的打印
        for (int v = 0; v < (height + mmH) / mmH; v++) {
            canvas.drawLine(0, 0 + v * mmH, endX, 0 + v
                    * mmH, mPaint);
        }
        // 导联I和导联II的Y轴上下间隔。
        int jiangeY = picHeight / 12;
        int jiangeX = 0;
        // startDrawY开始的Y
        /********** 添加说明 **********/
        Paint textPaint = new Paint();
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextSize(36);
        // 从左边x开始baseX；
        int baseX = 50;
        startX1 = baseX;
        startY1 = startDrawY + jiangeY / 2;
        startX2 = baseX;
        startY2 = startY1 + jiangeY;
        startX3 = baseX;
        startY3 = startY2 + jiangeY;
        startX22 = baseX;
        startY22 = startY3 + jiangeY;

        startXvr = baseX + jiangeX;
        startYvr = startY3 + jiangeY;
        startXvl = baseX + jiangeX;
        startYvl = startYvr + jiangeY;
        startXvf = baseX + jiangeX;
        startYvf = startYvl + jiangeY;

        startXv1 = baseX + jiangeX * 2;
        startYv1 = startYvf + jiangeY;
        startXv2 = baseX + jiangeX * 2;
        startYv2 = startYv1 + jiangeY;
        startXv3 = baseX + jiangeX * 2;
        startYv3 = startYv2 + jiangeY;

        startXv4 = baseX + jiangeX * 3;
        startYv4 = startYv3 + jiangeY;
        startXv5 = baseX + jiangeX * 3;
        startYv5 = startYv4 + jiangeY;
        startXv6 = baseX + jiangeX * 3;
        startYv6 = startYv5 + jiangeY;
        // 因为文字和波形图重叠了。所以文字的Y减去一点
        int textjianY = 10;
        // startDrawX空白的开始画图的地方
        canvas.drawText("I", startX1, startY1 - 10, textPaint);
        canvas.drawText("II", startX2, startY2 - 10, textPaint);
        canvas.drawText("III", startX3, startY3 - 10, textPaint);
        // canvas.drawText("II", startX22, startY22-10, textPaint);
        canvas.drawText("aVR", startXvr, startYvr - 10, textPaint);
        canvas.drawText("aVL", startXvl, startYvl - 10, textPaint);
        canvas.drawText("aVF", startXvf, startYvf - 10, textPaint);
        canvas.drawText("V1", startXv1, startYv1 - 10, textPaint);
        canvas.drawText("V2", startXv2, startYv2 - 10, textPaint);
        canvas.drawText("V3", startXv3, startYv3 - 10, textPaint);
        canvas.drawText("V4", startXv4, startYv4 - 10, textPaint);
        canvas.drawText("V5", startXv5, startYv5 - 10, textPaint);
        canvas.drawText("V6", startXv6, startYv6 - 10, textPaint);
    }

    static int startX1;
    static int startY1;
    static int startX2;
    static int startY2;
    static int startX3;
    static int startY3;
    static int startX22;
    static int startY22;

    static int startXvr;
    static int startYvr;
    static int startXvl;
    static int startYvl;
    static int startXvf;
    static int startYvf;

    static int startXv1;
    static int startYv1;
    static int startXv2;
    static int startYv2;
    static int startXv3;
    static int startYv3;

    static int startXv4;
    static int startYv4;
    static int startXv5;
    static int startYv5;
    static int startXv6;
    static int startYv6;

    /**
     * @param canvas
     * @param report1
     * @param name
     * @param sex
     * @param age
     * @param checkTime
     * @param idCard
     * @param result
     * @param hospital
     */
    private static void drawECGResult(Canvas canvas, int[] report1,
                                      String name, String sex, String age, String checkTime,
                                      String idCard, String result, String hospital, boolean printResult) {
        int allWidth = canvas.getWidth(), allHeight = canvas.getHeight();
        // 图片的宽度
        Paint textPaint = new Paint();
        int textSize = 42;
        textPaint.setStrokeWidth(2);
        textPaint.setDither(true);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextSize(textSize);
        textPaint.setColor(color_title);
        // 下一个开始的x位置，就是上面已经画好的，然后从nextStartX开始画
        int nextStartY = 0 + 30;
        int startX = canvas.getWidth() / 4 * 3 - 60;
        nextStartY += textSize;
        canvas.drawText("测量时间：" + checkTime, startX, nextStartY, textPaint);
        nextStartY += textSize;
        // 将身份号替换月日为****
        idCard = idCard.substring(0, idCard.length() - 8) + "****"
                + idCard.substring(idCard.length() - 4, idCard.length());
        canvas.drawText("身份证号:" + idCard, startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("姓名：" + name, startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("性别：" + sex + " 年龄：" + age, startX, nextStartY,
                textPaint);
        nextStartY += textSize;
        canvas.drawText("医院名称：" + hospital, startX, nextStartY, textPaint);
        nextStartY += textSize;
        nextStartY += textSize;
        // canvas.drawLine(0, textSize + 6, allWidth, textSize + 6, textPaint);
        textPaint.setColor(Color.BLACK);
        int firstWidth = 170;
        int dataWidth = firstWidth + 160;
        int secondWidth = dataWidth + 210;
        String hr = report1[0] + "";
        String pr_jq = report1[1] / 10 + "";
        String qrs_sx = report1[2] / 10 + "";
        String qt_jq = report1[3] / 10 + "";
        String qtc_jq = report1[4] / 10 + "";
        String p_dz = report1[5] / 10 + "";
        String qrs_dz = report1[6] / 10 + "";
        String t_dz = report1[7] / 10 + "";

        String rv5_dy = report1[8] / 100.00 + "";
        String sv1_dy = report1[9] / 100.00 + "";
        double fiveaddone = Double.valueOf(report1[8] / 100.00 + report1[9] / 100.00);
        long l1 = Math.round(fiveaddone * 100); //四舍五入
        double ret = l1 / 100.00; //注意:使用 100.0 而不是 100
        String rv5addsv1 = String.format("%.2f", ret);
//        fiveaddone=1.7999999;
//        DecimalFormat df = new DecimalFormat("#.##");
//        String rv5addsv1 = df.format(fiveaddone);
//        double d = 3.14159;
//        System.out.println();


        canvas.drawText("HR ", 0 + startX, nextStartY, textPaint);
        canvas.drawText("心率", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(hr, dataWidth + startX, nextStartY, textPaint);
        canvas.drawText("bmp", secondWidth + startX, nextStartY, textPaint);
        String[] results = result.split("\n");

        nextStartY += textSize;
        canvas.drawText("PR ", 0 + startX, nextStartY, textPaint);
        canvas.drawText("间期", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(pr_jq, dataWidth + startX, nextStartY, textPaint);
        canvas.drawText("ms", secondWidth + startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("QRS", 0 + startX, nextStartY, textPaint);
        canvas.drawText("时限", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(qrs_sx, dataWidth + startX, nextStartY, textPaint);
        canvas.drawText("ms", secondWidth + startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("QT/QTC", 0 + startX, nextStartY, textPaint);
        canvas.drawText("间期", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(qt_jq + "/" + qtc_jq, dataWidth + startX, nextStartY,
                textPaint);
        canvas.drawText("ms", secondWidth + startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("P/QRS/T", 0 + startX, nextStartY, textPaint);
        canvas.drawText("电轴", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(p_dz + "/" + qrs_dz + "/" + t_dz, dataWidth + startX,
                nextStartY, textPaint);
        canvas.drawText("°", secondWidth + startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("RV5/SV1", 0 + startX, nextStartY, textPaint);
        canvas.drawText("电压", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(rv5_dy + "/" + sv1_dy, dataWidth + startX, nextStartY,
                textPaint);
        canvas.drawText("mV", secondWidth + startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("RV5+SV1", 0 + startX, nextStartY, textPaint);
        canvas.drawText("电压", firstWidth + startX, nextStartY, textPaint);
        canvas.drawText(rv5addsv1, dataWidth + startX, nextStartY, textPaint);
        canvas.drawText("mV", secondWidth + startX, nextStartY, textPaint);
        nextStartY += textSize;
        canvas.drawText("  [ 25mm/S ] [ 10mm/mV ]", 0 + startX, nextStartY,
                textPaint);
        nextStartY += textSize;
        nextStartY += textSize;
        int tempY = nextStartY;
        if (printResult) {
            for (int i = 0; i < results.length; i++) {
                canvas.drawText(results[i], 0 + startX, tempY, textPaint);
                tempY += textSize;
            }
        }
        nextStartY = tempY;
        nextStartY += textSize;
        canvas.drawText("未确定报告,需医生确认:_ _ _ _ _ _ _", startX, allHeight - 50,
                textPaint);
    }

    /***
     * 画心电图线。
     *
     * @param ecgDatas
     *            集合，每个元素存放一个导联的int数组
     * @param canvas
     */
    private static void drawECGValue(ArrayList<int[]> ecgDatas, Canvas canvas) {
        /********** 画心电图线 **********/
        drawECGGraph(startY1, ecgDatas.get(0), 1, canvas); // I
        drawECGGraph(startY2, ecgDatas.get(1), 2, canvas); // II
        drawECGGraph(startY3, ecgDatas.get(2), 3, canvas); // III
        drawECGGraph(startYvr, ecgDatas.get(3), 4, canvas); // aVR
        drawECGGraph(startYvl, ecgDatas.get(4), 5, canvas); // aVL
        drawECGGraph(startYvf, ecgDatas.get(5), 6, canvas); // aVF
        drawECGGraph(startYv1, ecgDatas.get(6), 7, canvas); // v1
        drawECGGraph(startYv2, ecgDatas.get(7), 8, canvas); // v2
        drawECGGraph(startYv3, ecgDatas.get(8), 9, canvas); // v3
        drawECGGraph(startYv4, ecgDatas.get(9), 10, canvas); // v4
        drawECGGraph(startYv5, ecgDatas.get(10), 11, canvas); // v5
        drawECGGraph(startYv6, ecgDatas.get(11), 12, canvas); // v6
    }

    public static double xWidth = 0.9;

    private static final float gain = 0.32f;

    private static void drawECGGraph(int base, int[] ecgDatas, int tag,
                                     Canvas canvas) {
        Paint mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(3);
        ArrayList<Integer> oneList = null;
        int maxCount = ecgDatas.length / 11 * 8;
        float baseX;
//		base += 5;
        switch (tag) {
            case 1:
                oneList = new ArrayList<Integer>();
                baseX = startX1 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
            case 2:
                oneList = new ArrayList<Integer>();
                baseX = startX2 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 3:
                oneList = new ArrayList<Integer>();
                baseX = startX3 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 4:
                oneList = new ArrayList<Integer>();
                baseX = startXvr + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 5:
                oneList = new ArrayList<Integer>();
                baseX = startXvl + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 6:
                oneList = new ArrayList<Integer>();
                baseX = startXvf + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 7:
                oneList = new ArrayList<Integer>();
                baseX = startXv1 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 8:
                oneList = new ArrayList<Integer>();
                baseX = startXv2 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 9:
                oneList = new ArrayList<Integer>();
                baseX = startXv3 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 10:
                oneList = new ArrayList<Integer>();
                baseX = startXv4 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 11:
                oneList = new ArrayList<Integer>();
                baseX = startXv5 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 12:
                oneList = new ArrayList<Integer>();
                baseX = startXv6 + 20;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            case 22:
                oneList = new ArrayList<Integer>();
                baseX = startX22 + 20;
                maxCount = ecgDatas.length;
                for (int i = 0; i < ecgDatas.length; i++) {
                    int y = convertY2Pix(base, ecgDatas[i]);
                    oneList.add(y);
                }
                for (int j = 0; j < oneList.size() - 1 && j < maxCount; j++) {
                    canvas.drawLine((float) (j * xWidth + baseX),
                            (float) oneList.get(j),
                            (float) ((j + 1) * xWidth + baseX),
                            (float) oneList.get(j + 1), mPaint);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 根据int[]数组的幅度值，来获取
     *
     * @param base
     * @param y
     * @return
     */
    private static int convertY2Pix(int base, int y) {
        // 60/160=0.375
        double newValue = base + (-(y) * 0.667 * gain);
        int value = newValue >= 0 ? (int) (newValue + 0.5)
                : (int) (newValue - 0.5);
        // Log.i("value", "base =" + base + " " + "value =" + "" + value);
        return value;
    }

    /***
     * 获取自定义字号的中文字体
     *
     * @param textSize
     * @return
     */
    public static Font getChineseFont(int textSize) {
        BaseFont bf = null;
        Font fontChinese = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, textSize, Font.NORMAL, BaseColor.BLACK);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    /***
     * 默认12号的中文字体。
     *
     * @return
     */
    public static Font getChineseFont() {
        BaseFont bf = null;
        Font fontChinese = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);

            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    private static byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    // 产生PDF字体
    public static Font setChineseFont() {
        BaseFont bf = null;
        Font fontChinese = null;
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

    public static void savePDFFile(String textContent, Bitmap bitmap,
                                   String filePath) {
        Document document = new Document(PageSize.A4.rotate(), 5, 5, 5, 5);
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            PdfWriter.getInstance(document, fos);
            // step 3: we open the document
            document.open();
            // step 4:
            document.add(new Paragraph(textContent));
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Bitmap bitmap2 = small(bitmap);
            // Bitmap bitmap = resizeBitMapImage1(pngPath, 720, 480);
            bitmap.compress(Bitmap.CompressFormat.PNG /* FileType */,
                    100 /* Ratio */, stream);
            Image jpg = Image.getInstance(stream.toByteArray());
            jpg.scalePercent(0.65f);
            // Image jpg = Image.getInstance(pngPath);
            jpg.setAlignment(Image.MIDDLE);
            // document.add(jpg);
        } catch (Exception e) {
            System.out.println("保存打印文件失败。。。");
            e.printStackTrace();
        }
        document.close();
    }

    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.62f, 0.62f); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    private static Bitmap small(Bitmap bitmap, float sx, float sy) {
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    public static Bitmap big(Bitmap b, float x, float y) {
        int w = b.getWidth();
        int h = b.getHeight();
        float sx = (float) x / w;// 要强制转换，不转换我的在这总是死掉。
        float sy = (float) y / h;
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w, h, matrix, true);
        return resizeBmp;
    }

    public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,
                                            int targetHeight) {
        Bitmap bitMapImage = null;
        // First, get the dimensions of the image
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        double sampleSize = 0;
        // Only scale if we need to
        // (16384 buffer for img processing)
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
                .abs(options.outWidth - targetWidth);
        if (options.outHeight * options.outWidth * 2 >= 1638) {
            // Load, scaling to smallest power of 2 that'll get it <= desired
            // dimensions
            sampleSize = scaleByHeight ? options.outHeight / targetHeight
                    : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        // Do the actual decoding
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeFile(filePath, options);
                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {
                }
            }
        }
        return bitMapImage;
    }

    /***
     * 获取assets中的txt文件的字符串数据
     *
     * @param context
     * @param fileName
     * @return txt的字符串数据
     */
    /*
     * public static int[] getAssetsString(Context context, String fileName) {
	 * String result = ""; InputStream inputStream; StringBuilder sb = null; try
	 * { inputStream = context.getResources().getAssets().open(fileName);
	 * InputStreamReader inputStreamReader; inputStreamReader = new
	 * InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader =
	 * new BufferedReader( inputStreamReader); String line = ""; sb = new
	 * StringBuilder(); int s = bufferedReader.read(); System.out.println(s);
	 * while ((line = bufferedReader.readLine()) != null) { sb.append(line); }
	 * sb.toString(); } catch (IOException e) { e.printStackTrace(); } return
	 * string2Ints(sb.toString()); }
	 */

    /***
     * 将字符串转化为一个int数组。
     *
     * @param intsString
     * @return 返回一个int数组
     */
    public static int[] string2Ints(String intsString) {
        if (intsString == null) {
            intsString = "";
        }
        String[] strArray = intsString.trim().split(",");
        int[] result = new int[strArray.length];
        for (int i = 0; i < strArray.length; i++) {
            result[i] = Integer.parseInt(strArray[i]);
        }
        return result;
    }

    /***
     * 获取用来展示的心电假数据
     *
     * @param context
     * @return
     */
    /*
     * public static ArrayList<int[]> getShowECGDatas(Context context) {
	 * ArrayList<int[]> result = new ArrayList<int[]>(); for (int i = 0; i < 12;
	 * i++) { int[] temp = getAssetsString(context, "ecg/导联" + i + ".txt");
	 * result.add(temp); } return result; }
	 */
}
